//
//  APIRequesstBase.m
//  mmspc
//
//  Created by list on 2017/9/25.
//  Copyright © 2017年 com.abc.mmsp. All rights reserved.
//

#import "APIRequesstBase.h"
//#import "Utility.h"
//#import "ABCLoginViewController.h"
#import "AppDelegate.h"
#import "YTKNetwork.h"
@implementation APIRequesstBase
- (NSDictionary *)requestHeaderFieldValueDictionary {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return @{
             @"dev-id": @"[Utility deviceID]",
             @"os-type": @"02",
             @"os-ver":@"[Utility systemVersion]",
             @"dnfl-token":@"[[GlobalSettings sharedInstance] dnfltoken]",
             @"app-ver":app_Version
             };
}

- (void)requestCookie{
    NSLog(@"requestCookie in base");
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",[YTKNetworkConfig sharedConfig].baseUrl,@"ABC_API_LOGIN"]]];
    NSMutableArray* cookieToset = [NSMutableArray arrayWithArray:cookies];
    for (NSHTTPCookie* cookie in cookieToset) {
        NSLog(@"cookie.name:%@",cookie.name);
        if ([cookie.name isEqualToString:@"RM_TOKEN"]) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
        }
    }
}

- (void)startRequestWithBlockSuccess:(nullable ABCAPIResponseBlock)success
                             failure:(nullable ABCAPIResponseBlock)failure{
    NSLog(@"start request:%@",self.requestUrl);
    
    NSArray* blackList = @[@"ABC_API_LOGIN"];
    BOOL inBlack = [blackList containsObject:self.requestUrl];
    __weak __typeof(self) weakSelf = self;
    self.successResponseBlock = success;
    self.failureResponseBlock = failure;
    [self requestCookie];
    [self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"success in base :%@",request.requestUrl);
        
        YTKResponseSerializerType responseType = request.responseSerializerType;
        switch (responseType) {
            case YTKResponseSerializerTypeJSON:
            {
                if (![NSJSONSerialization isValidJSONObject:request.responseObject]) {
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.returnCode = @"-1";
                    response.returnMessage = NSLocalizedStringFromTable(@"abc_data_format_error", @"constant", nil);
                    response.request = request;
                    
                    weakSelf.failureResponseBlock(response);
                    return ;
                }else{
                    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
                    NSString* returnCode = json[@"retCode"];
                    NSString* returnMsg = json[@"retMsg"];
                    NSString* returnData = json[@"data"];
                    if(returnCode.integerValue == 1 && inBlack == NO){
                        if(![request.requestUrl containsString:@"queryocrmorg"]){
                          
                        }
                    }
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.returnCode = returnCode;
                    response.returnMessage = returnMsg;
                    response.returnData = returnData;
                    response.request = request;
                    weakSelf.successResponseBlock(response);
                }
            }
                break;
            case YTKResponseSerializerTypeHTTP:
            {
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.request = request;
                
                weakSelf.successResponseBlock(response);
            }
                break;
            default:
            {
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.returnCode = @"-1";
                response.returnMessage = NSLocalizedStringFromTable(@"abc_data_format_error", @"constant", nil);
                response.request = request;
                
                weakSelf.failureResponseBlock(response);
            }
                break;
        }

    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"failed in base :%@",request.requestUrl);
        NSInteger statusCode = request.responseStatusCode;
        if (statusCode == 401 && request && request.responseData) {
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
            NSString* returnCode = json[@"retCode"];
            if (returnCode && [returnCode integerValue] == 2) {
                [weakSelf returnCode_2_Operation];
                
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.returnCode = returnCode;
                response.request = request;
                weakSelf.failureResponseBlock(response);
                return ;
            }
        }else{
            
            ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
            response.returnCode = @"-1";
            response.returnMessage = NSLocalizedStringFromTable(@"abc_network_error", @"constant", nil);
            response.returnData = nil;
            response.request = request;
            
            if(request.error.code == -1001){//超时
                
                weakSelf.failureResponseBlock(response);
                return;
            }
            //NSURLErrorCode 网络错误码
            NSString* alertMessage = [NSString stringWithFormat:@"%@ 错误码:%ld,状态码:%ld", NSLocalizedStringFromTable(@"abc_network_error", @"constant", nil),(long)request.error.code,(long)request.response.statusCode];
            
            
            
            weakSelf.failureResponseBlock(response);
            
        }
    }];
}
- (void)startRequestWithHideAlertWhenFinish:(BOOL)hidden success:(nullable ABCAPIResponseBlock)success failure:(nullable ABCAPIResponseBlock)failure{
    NSLog(@"start request:%@",self.requestUrl);
    
    NSArray* blackList = @[@"ABC_API_LOGIN"];
    BOOL inBlack = [blackList containsObject:self.requestUrl];
    __weak __typeof(self) weakSelf = self;
    self.successResponseBlock = success;
    self.failureResponseBlock = failure;
    [self requestCookie];
    [self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"success in base :%@",request.requestUrl);
        if (hidden) {
            
        }
        YTKResponseSerializerType responseType = request.responseSerializerType;
        switch (responseType) {
            case YTKResponseSerializerTypeJSON:
            {
                if (![NSJSONSerialization isValidJSONObject:request.responseObject]) {
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.returnCode = @"-1";
                    response.returnMessage = NSLocalizedStringFromTable(@"abc_data_format_error", @"constant", nil);
                    response.request = request;
                    
                    weakSelf.failureResponseBlock(response);
                    return ;
                }else{
                    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
                    NSString* returnCode = json[@"retCode"];
                    NSString* returnMsg = json[@"retMsg"];
                    NSString* returnData = json[@"data"];
                    if(returnCode.integerValue == 1 && inBlack == NO){
                        if(![request.requestUrl containsString:@"queryocrmorg"]){
                          
                        }
                    }
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.returnCode = returnCode;
                    response.returnMessage = returnMsg;
                    response.returnData = returnData;
                    response.request = request;
                    weakSelf.successResponseBlock(response);
                }
            }
                break;
            case YTKResponseSerializerTypeHTTP:
            {
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.request = request;
                
                weakSelf.successResponseBlock(response);
            }
                break;
            default:
            {
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.returnCode = @"-1";
                response.returnMessage = NSLocalizedStringFromTable(@"abc_data_format_error", @"constant", nil);
                response.request = request;
                
                weakSelf.failureResponseBlock(response);
            }
                break;
        }

    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"failed in base :%@",request.requestUrl);
        
        if (hidden) {
            
        }
        NSInteger statusCode = request.responseStatusCode;
        if (statusCode == 401 && request && request.responseData) {
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
            NSString* returnCode = json[@"retCode"];
            if (returnCode && [returnCode integerValue] == 2) {
                [weakSelf returnCode_2_Operation];
                
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.returnCode = returnCode;
                response.request = request;
                weakSelf.failureResponseBlock(response);
                return ;
            }
        }else{
            
            ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
            response.returnCode = @"-1";
            response.returnMessage = NSLocalizedStringFromTable(@"abc_network_error", @"constant", nil);
            response.returnData = nil;
            response.request = request;
            
            if(request.error.code == -1001){//超时
                
                weakSelf.failureResponseBlock(response);
                return;
            }
            //NSURLErrorCode 网络错误码
            NSString* alertMessage = [NSString stringWithFormat:@"%@ 错误码:%ld,状态码:%ld", NSLocalizedStringFromTable(@"abc_network_error", @"constant", nil),(long)request.error.code,(long)request.response.statusCode];
            
            
            
            weakSelf.failureResponseBlock(response);
            
        }
    }];
}
//actionOK action 待完善 放这里不太好
- (void)returnCode_2_Operation{
    NSDate* now = [NSDate date];
//    NSDate* expries = [[NSUserDefaults standardUserDefaults]objectForKey:RM_TOKEN_EXPIRES];
    NSDate* expries = [NSDate now];
    if (expries) {
        NSComparisonResult result = [now compare:expries];
        if (result == NSOrderedAscending){
            NSLog(@"now < expries");
           
            return;
            }
    }
    __weak __typeof(self) weakSelf = self;
    ;
}

- (void)resetSetting:(NSDictionary*)settings{
    NSLog(@"in baserequest settings[@isGesON]:%@,settings[@isFingerON]:%@,",settings[@"isGesON"],settings[@"isFingerON"]);

}
@end
